<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\Message;

class MessageBoardController extends Controller
{
    // dd($messages); // 打印数据并终止执行
    public function index(Request $request) {
        $query = $request->input('query');

        $messages = Message::with('user')->when($query, function ($queryBuilder, $searchTerm) {
            // 如果有搜索关键词，添加搜索条件
            return $queryBuilder->where('title', 'like', "%{$searchTerm}%")
                                ->orWhere('content', 'like', "%{$searchTerm}%");
        })
        ->latest()
        ->paginate(3);
        return view('board.index', compact('messages'));
    }

    // 显示创建表单
    public function create() {
        return view('board.create');
    }

    // 处理表单提交
    public function store(Request $request) {
        Message::create([
            'user_id' => Auth::id(),
            'title' => $request->title,
            'content' => $request->content,
        ]);

        return redirect()->route('messageboard.list')
            ->with('success', '留言发布成功！');
    }

    // 显示单个
    public function show(Message $message) {
        return view('board.show', compact('message'));
    }

    // 显示编辑
    public function edit(Message $message) {
        if (Auth::user()->can('do any thing') || auth()->id() === $message->user_id) {
            return view('board.edit', compact('message'));
        }
        return redirect()->route('messageboard.list')
            ->with('error', '你没有权限修改此留言！');
    }

    // 更新
    public function update(Request $request, Message $message) {
        if (Auth::user()->can('do any thing') || auth()->id() === $message->user_id) {
            //数据验证
            $validated = $request->validate([
                'title' => 'required|string|max:100',
                'content' => 'required|string',
            ]);
            $message->update([
                'title' => $validated['title'],
                'content' => $validated['content'],
            ]);
            return redirect()->route('messageboard.list')
                ->with('success', '留言已修改！');
        }
        return redirect()->route('messageboard.list')
            ->with('error', '你没有权限修改此留言！');
    }

    // 删除
    public function destroy(Message $message) {
        if (Auth::user()->can('do any thing') || auth()->id() === $message->user_id) {
            $message->delete();
            return redirect()->route('messageboard.list')
                ->with('success', '留言已删除！');
        }
        return redirect()->route('messageboard.list')
            ->with('error', '你没有权限删除此留言！');
    }
}
